package com.wyfan.scaffold.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常拦截
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 系统异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
        log.error(ex.getMessage(),ex);
        return Result.ofException(ResultType.FAIL.getCode(),ex);
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = UserException.class)
    @ResponseBody
    public Result apiErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, UserException ex){
        return ex.getResult();
    }
}
